package com.sherlocky.resource.web;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sherlocky.common.BaseController;
import com.sherlocky.resource.common.ResourceContants;
import com.sherlocky.resource.dao.ResourceDAO;
import com.sherlocky.resource.dto.ResourceDTO;
import com.sherlocky.resource.service.ResourceService;
import com.sherlocky.util.FileUtil;

@Controller
@RequestMapping
public class ResourceMappingController extends BaseController{
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private ResourceDAO resourceDAO;
	
	/**
	 * 读取转码音视频
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value=ResourceContants.MEDIA_URL+"{id}")
	public void loadVideo(@PathVariable Long id, HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		if(id == null){
			logger.error("[id 获取失败："+id+"]");
			return ;
		}
		anonymousAccessControll(request, String.valueOf(id));
		ResourceDTO resource = resourceService.getResourceById(id);
		String transferPath = resourceService.getTransfilePath(resource);
		String contextType = "video/x-flv";
		if("mp3".equalsIgnoreCase(get(request, "fileType")) || StringUtils.endsWithIgnoreCase(transferPath, ".mp3")) {
			transferPath = StringUtils.replace(transferPath, ".flv", ".mp3");
			contextType = "audio/mp3";
		}
		if( StringUtils.isNotBlank(transferPath) && FileUtil.isExistsFile(transferPath) ) {
			File file = new File(transferPath);
			if(!file.exists()) {
				logger.error("找不到文件[" + transferPath + "]");
				return;
			}
			try{
				outputStream(response, file, contextType, null);
			} catch (Exception ex) {
				logger.error("播放视频时发生错误:" + ex.getMessage(),ex);
			}
		}
	}
}
